<template>
  <div class="login">
    <!-- 导航栏  -->
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      placeholder
      fixed
      @click-left="$router.go(-1)"
    />

    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="用户名"
        placeholder="用户名"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="password"
        name="code"
        label="密码"
        placeholder="密码"
        :rules="[
          { required: true, message: '验证码没有写哦!' },
          { pattern: /\d{6}/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoding"
          :loading="isLoding"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from './user.js'
import { saveToken } from '@/utils/token.js'

export default {
  name: 'login',
  data () {
    return { code: '246810', mobile: '', isLoding: false, userInfo: {} }
  },
  methods: {
    // 提交时间，发送请求请求
    onSubmit (value) {
      this.isLoding = true
      userLogin(value)
        .then(res => {
          console.log(res)
          //调用已经封装 好的工具包 将返回的数据保存在localStorge中
          this.$toast.success('登录成功')

          saveToken(res.data.data)
          // 登录成功跳转页面到首页
          this.$router.push({ path: '/home' })
        })
        .catch(err => {
          this.$toast.fail('登录失败')
        })
        .then(() => {
          this.isLoding = false
        })
    }
  }
}
</script>

<style lang="less">
.login {
  .van-nav-bar {
    background-color: #0098fa;
    .van-nav-bar__text {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
